package com.rr.springcloud.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @author RR
 * @date 2021/3/31 20:40
 */
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(GatewayFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("===enter gateway filter===" + "===time:{}===", new Date());
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (username == null || "".equals(username)) {
            logger.info("===没有用户名，拒绝访问===");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        //效验通过则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //数字越小优先级越高
        return 0;
    }
}
